package com.gzittc.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet  {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 接受客户端传递参数
        response.setCharacterEncoding("UTF-8");
        // 接受客户端传递参数
        String uname = request.getParameter("uname");
        String upwd = request.getParameter("upwd");

        // 校验用户名和密码是否为空
        if (uname == null || "".equals(uname.trim())) {
            request.setAttribute("msg", "用户名不能为空");
            // 请求转发跳转到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        if (upwd == null || "".equals(upwd.trim())) {
            request.setAttribute("msg", "密码不能为空");
            // 请求转发跳转到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 判断用户名是否正确 uname = "admin" upwd = "admin"
        if (!"admin".equals(uname) || !"admin".equals(upwd)) {
            request.setAttribute("msg", "登录失败！");
            // 请求转发跳转到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 登录成功
        // 设置登录信息到session中
        request.getSession().setAttribute("uname", uname);
        // 跳转到index.jsp
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}
